def pinyin_stream_decode_2gram(p2g,ml,temple_result,pinyin,beam_size=100,p2g_dict=None,p2g_t=None,p2g_d=None):
    cur_words=p2g(pinyin,p2g_dict,*p2g_t,**p2g_d)
    if len(cur_words)==0:
        return []
    if len(temple_result)==0:
        lst_result=list()
        for word in cur_words:
            lst_result.append([word,1.0])
        return lst_result
    
    new_result=list()
    for sequence in temple_result:
        for cur_word in cur_words:
            tuple2_word=sequence[0][-1]+cur_word
            cur_prob=ml(sequence[1],tuple2_word)
            if cur_prob is not None:
                new_result.append([sequence[0]+cur_word,cur_prob])
    
    new_result=sorted(new_result,key=lambda x:x[1],reverse=True)
    if len(new_result)>beam_size:
        return new_result[0:beam_size]
    return new_result

def decode_chinese_pinyin2word_2gram(p2g,ml,pinyin_seq,beam_size=100,p2g_dict=None,p2g_t=None,p2g_d=None):
    result=list()
    tmp_result_last=list()
    for pinyin in pinyin_seq:
        tmp_result=pinyin_stream_decode_2gram(p2g,ml,tmp_result_last,pinyin,beam_size,p2g_dict=p2g_dict,p2g_t=p2g_t,p2g_d=p2g_d)
        # print(tmp_result)
        if len(tmp_result)==0 and len(tmp_result_last)>0:
            result.append(tmp_result_last[0][0])
            tmp_result=pinyin_stream_decode_2gram(p2g,ml,[],pinyin,beam_size,p2g_dict=p2g_dict,p2g_t=p2g_t,p2g_d=p2g_d)
            # if len(tmp_result)>0:
            #     result.append(tmp_result[0][0])
            # tmp_result=[]
        # elif len(tmp_result_last)>0 and tmp_result_last[0][1]<1e-10:
        #     result.append(tmp_result_last[0][0])
        #     tmp_result = pinyin_stream_decode_2gram(p2g,ml,[], item_pinyin, beam_size)
        tmp_result_last=tmp_result
    if len(tmp_result_last)>0:
        result.append(tmp_result_last[0][0])
    return ''.join(result)